//
//  ViewController.m
//  19-JSON网易新闻
//
//  Created by dllo on 16/8/9.
//  Copyright © 2016年 DM.C. All rights reserved.
//

#import "ViewController.h"
#import "NewsTitle.h"
#import "NewsCollectionViewCell.h"
#import "NetEaseTitleLayout.h"
@interface ViewController ()<UICollectionViewDataSource, UICollectionViewDelegate, NetEaseTitltLayoutDelegate>
@property (weak, nonatomic) IBOutlet UICollectionView *myCollectionView;
@property (nonatomic, strong) NSMutableArray<NewsTitle *> *newsTitleArray;
@property (nonatomic, strong) NetEaseTitleLayout *layout;
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    _newsTitleArray = [NSMutableArray array];
    [self handleData];
   self.layout = (NetEaseTitleLayout *)self.myCollectionView.collectionViewLayout;
    _layout.delegate = self;
    _layout.titleFont = [UIFont systemFontOfSize:22];
    _myCollectionView.backgroundColor = [UIColor whiteColor];
}
- (void)handleData {
    // 找到文件路径
    NSString *newsJSON = [[NSBundle mainBundle] pathForResource:@"news" ofType:@"json"];
    // 转换data数据
    NSData *JSONData = [NSData dataWithContentsOfFile:newsJSON];
    // JSON解析
    NSDictionary *newsTitleDic = [NSJSONSerialization JSONObjectWithData:JSONData options:NSJSONReadingMutableContainers error:nil];
    // 层层解析数据
    NSArray *listArray = [newsTitleDic objectForKey:@"tList"];
    
    for (NSDictionary *dic in listArray) {
        NewsTitle *news = [NewsTitle newsTitleDic:dic];
        [_newsTitleArray addObject:news];
    }
}
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout string:(NSString *)string stringFont:(UIFont *)font widthForItemAtIndexPath:(NSIndexPath *)indexPath {
    NewsTitle *news = _newsTitleArray[indexPath.row];
    CGRect newRet = [news.tname boundingRectWithSize:CGSizeMake(CGFLOAT_MAX, CGRectGetHeight(self.myCollectionView.bounds)) options:1 attributes:@{NSFontAttributeName : _layout.titleFont} context:nil];
    CGFloat width = ceil(newRet.size.width);
    return width;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return _newsTitleArray.count;
}
- (__kindof UICollectionViewCell *) collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    NewsCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"reuse" forIndexPath:indexPath];
    cell.news = _newsTitleArray[indexPath.row];
    cell.labelOfTitle.font = [UIFont systemFontOfSize:22];
    return cell;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


@end
